<?php

require_once 'PipesImpl/Database/Reflection/Column.php';
require_once 'PipesImpl/Database/Reflection/Table.php';
require_once 'Pipes/Exception.php';

class Pipes_Database_Reflection_Column implements PipesImpl_Database_Reflection_Column
{
	private $_pdo = null;
	private $_table = null;
	private $_name = '';
	
	public function __construct(PipesImpl_Database_Reflection_Table $table, $name) {
		$this->_name = $name;
		$this->_table = $table;
		$this->_pdo = $table->getPDO();
		$query = 'DESCRIBE ' . $this->_table->getName() . ' ' . $this->_name;
		
		$statement = $this->_pdo->query($query);
		if (!$statement) {
			throw new Pipes_Exception();
		}
		$this->_data = $statement->fetch();
	}
	
	public function getName() {
		return $this->_data['Field'];
	}
	
	public function getType() {
		preg_match('/^([A-Za-z]+)/', $this->_data['Type'], $matches);
		list(, $type) = each($matches);
		return strtoupper($type);
	}
	
	public function getLength() {
		if (preg_match('/^([A-Za-z]+)\(([0-9]+)\)/', $this->_data['Type'], $matches)) {
			$length = $matches[2];
			return $length;
		}
	}
	
	public function getDefault() {
		return $this->_data['Default'];
	}
	
	public function isRequired() {
		return $this->_data['Null'] == 'YES' ? false : true;
	}
	
	public function isTableId() {
		return (substr($this->_table->getName(), 0, -1) . '_id' == $this->getName());
	}
}
